package com.sky.sky_server.config;

import java.util.List;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.lang.NonNull;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.sky.sky_common.json.JacksonObjectMapper;
import com.sky.sky_server.interceptor.JwtTokenAdminInterceptor;
import com.sky.sky_server.interceptor.JwtTokenUserInterceptor;

import lombok.extern.slf4j.Slf4j;

@Configuration
@Slf4j
public class WebConfig implements WebMvcConfigurer {

    private final JwtTokenAdminInterceptor jwtTokenAdminInterceptor;
    private final JwtTokenUserInterceptor jwtTokenUserInterceptor;

    public WebConfig(JwtTokenAdminInterceptor jwtTokenAdminInterceptor, JwtTokenUserInterceptor jwtTokenUserInterceptor) {
        this.jwtTokenAdminInterceptor = jwtTokenAdminInterceptor;
        this.jwtTokenUserInterceptor = jwtTokenUserInterceptor;
    }

    @Override
    public void addInterceptors(@NonNull InterceptorRegistry registry) {
        // 注册管理员拦截器
        registry.addInterceptor(jwtTokenAdminInterceptor)
        .addPathPatterns("/admin/**") // 拦截所有/admin请求
        .excludePathPatterns("/admin/employee/login", "/admin/employee/logout", "/error/**", "/static/**"); // 排除登录请求

        // 注册用户拦截器
        registry.addInterceptor(jwtTokenUserInterceptor)
        .addPathPatterns("/user/**") // 拦截所有/user请求
        .excludePathPatterns("/user/user/login", "/user/user/web/login", "/user/user/logout", "/user/shop/status"); // 排除用户登录请求

    }

    @Override
    public void extendMessageConverters(@NonNull List<HttpMessageConverter<?>> converters) {
        log.info("扩展消息转换器. to json");
        // 创建一个消息转换器对象
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        // 需要为消息转换器设置一个对象转换器，对象转换器可以将java对象序列化为json数据
        converter.setObjectMapper(new JacksonObjectMapper());
        // 将自己的消息转化器加入到容器中,并设置高优先级，保证比其他系统预定义的先执行
        converters.add(0, converter);
    }

}
